// pages/ChatBox/ChatBox.js
const app = getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Chat:[],
    myOpenid:''
  },
  return:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  news:function(e){
    console.log(e)
    console.log(e.currentTarget.id)
    wx.navigateTo({
      url: "/pages/ShopAdmin/ChatRoom/ChatRoom?id=" +e.currentTarget.id+ "",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getChat:function(Openid){
    var that = this
    db.collection('Chat').where({
      SellOpenid: Openid
    })
    .get({
      success: function(res) {
        // res.data 是包含以上定义的两条记录的数组
        console.log(res.data.length)
        for (let i = 0; i < res.data.length;i++){
          var id = "Chat[" + i + "].id"
          var nickName = "Chat[" + i + "].nickName"
          var avatarUrl = "Chat[" + i + "].avatarUrl"
          var Openids = "Chat[" + i + "].Openids"
          var Times = "Chat[" + i + "].Times"
          var Titles = "Chat[" + i + "].Titles"
          var GoodsId = "Chat[" + i + "].GoodsId"
          if(res.data[i].Openids.length!=0){
            that.setData({
              [nickName]: res.data[i].nickName,
              [id]: res.data[i]._id,
              [GoodsId]: res.data[i].GoodsId,
              [Openids]: res.data[i].Openids[res.data[i].Openids.length-1],
              [avatarUrl]: res.data[i].avatarUrl,
              [Times]: res.data[i].Times[res.data[i].Times.length-1],
              [Titles]: res.data[i].Titles[res.data[i].Titles.length-1],
            })
          }
          
          console.log( that.data.Chat)
          wx.hideLoading();
        }
      }
    }) 
  },
  onLoad: function (options) {
    // console.log(app.user.openid)
    // this.setData({
    //   myOpenid:app.user.openid
    // })
    // this.getChat(app.user.openid)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(app.user.openid)
    this.setData({
      Chat:[]
    })
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: "login"
    }).then(res => {
      console.log(res.result.openid);
      this.getChat(res.result.openid)
    }).catch(err => {
      console.log(err);
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})